<template>
  <el-dialog
    :title="`${drawerProps.title}记事本`"
    v-model="drawerVisible"
    :draggable="true"
    :overflow="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="5vh"
    width="75vw"
    :destroy-on-close="true"
    class="safe-note-dialog"
  >
    <el-form
      ref="ruleFormRef"
      class="note-form"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      label-position="top"
    >
      <!-- 基本信息区域 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">
            <el-icon><Setting /></el-icon>
            基本信息
          </h3>
        </div>

        <el-row :gutter="20">
          <form-item title="记事本名称" prop="name" :title-span="3" :item-span="8">
            <el-input v-model="drawerProps.row.name" clearable placeholder="请输入记事本名称" maxlength="50" show-word-limit />
          </form-item>
          <form-item
            title="访问密码"
            :title-span="3"
            :item-span="5"
            prop="show_password"
            help="密码需包含数字、大小写字母、特殊字符，长度大8位"
          >
            <div class="password-input">
              <el-input
                type="password"
                show-password
                v-model="drawerProps.row.show_password"
                placeholder="请设置访问密码"
                maxlength="20"
              />
              <div class="password-strength">
                <el-icon v-if="isPasswordStrong(drawerProps.row.show_password)" class="success-icon">
                  <CircleCheckFilled />
                </el-icon>
                <el-icon v-else-if="drawerProps.row.show_password" class="error-icon">
                  <CircleCloseFilled />
                </el-icon>
              </div>
            </div>
          </form-item>
          <form-item title="是否公开" :title-span="3" :item-span="2">
            <el-switch v-model="drawerProps.row.open" active-text="公开" inactive-text="私密" inline-prompt />
          </form-item>
        </el-row>

        <el-row v-if="!drawerProps.row.open" :gutter="20">
          <form-item title="共享用户" :title-span="3" :item-span="8" help="选择可以访问此记事本的用户，留空则仅创建者可访问">
            <UserDialogSelect
              v-model="selectedUsers"
              placeholder="请选择共享用户"
              dialog-title="选择共享用户"
              :max-count="50"
              @change="handleUsersChange"
            />
          </form-item>
        </el-row>
      </div>

      <!-- 内容编辑区域 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">
            <el-icon><EditPen /></el-icon>
            笔记内容
          </h3>
          <el-text type="info" size="small"> 支持富文本编辑，内容将被加密存储 </el-text>
        </div>

        <div class="editor-container">
          <WangEditor v-model:value="show_content" :editor-config="editConfig" />
        </div>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { SafeNote } from "@/api/types/base";
import WangEditor from "@/components/WangEditor/index.vue";
import formItem from "@/components/application/form/form-item.vue";
import UserDialogSelect from "@/components/SelectFilter/user-dialog-select.vue";
import { BusinessType, BusinessOptType } from "@/enums/sysEnum";
import { useUserAction } from "@/hooks/useUserAction";
import { useUserStore } from "@/stores/modules/user";
import { IEditorConfig } from "@wangeditor/editor";
import { encryptData, decryptData } from "@/api/services/security";
import apiService from "@/api/services/apiService";
import { CircleCheckFilled, CircleCloseFilled, Setting, EditPen } from "@element-plus/icons-vue";
import { isPasswordStrong } from "@/utils";

const { addUserAction } = useUserAction(BusinessType.SAFE_NOTE);
const userStore = useUserStore();

const show_content = ref("");
const open_password = ref(true);
const selectedUsers = ref<any[]>([]);

const rules = reactive({
  name: [{ required: true, message: "请输入记事本名称" }],
  show_password: [{ required: true, message: "请输入记事本密码" }]
});

const editConfig: Partial<IEditorConfig> = {
  placeholder: "请输入笔记内容……",
  MENU_CONF: {}
};

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<SafeNote>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 处理用户选择变化
const handleUsersChange = (users: any[]) => {
  selectedUsers.value = users;
  drawerProps.value.row.sharedUsers = users.map((user: any) => user._id);
  drawerProps.value.row.sharedUserNames = users.map((user: any) => user.userName);
};

// 接收父组件传过来的环境
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  show_content.value = "";
  drawerProps.value.row.show_password = "";
  selectedUsers.value = [];
  open_password.value = true;

  if (drawerProps.value.title.indexOf("编辑") != -1) {
    if (drawerProps.value.row.password) {
      open_password.value = true;
      drawerProps.value.row.show_password = decryptData(drawerProps.value.row.password);
    }
    const curNote = await apiService.findOne<SafeNote>(drawerProps.value.tbName, { _id: drawerProps.value.row._id });
    if (curNote) {
      if (curNote.data.content) {
        show_content.value = decryptData(curNote.data.content);
      }
      // 加载已共享的用户信息
      if (curNote.data.sharedUsers && curNote.data.sharedUsers.length > 0) {
        try {
          const sharedUsersData = await apiService.find("users", {
            _id: { $in: curNote.data.sharedUsers }
          });
          if (sharedUsersData.data && Array.isArray(sharedUsersData.data)) {
            selectedUsers.value = sharedUsersData.data.map((user: any) => ({
              _id: user._id,
              userName: user.userName,
              orgId: user.orgId,
              orgName: user.orgName,
              avatar: user.avatar
            }));
          }
        } catch (error) {
          console.error("加载共享用户信息失败:", error);
        }
      }
    }
  } else {
    drawerProps.value.row.open = false;
  }

  drawerVisible.value = true;
};

// 提交数据（新增/编辑）环境
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  if (isPasswordStrong(drawerProps.value.row.show_password)) {
    ruleFormRef.value!.validate(async valid => {
      if (!valid) return;
      try {
        if (drawerProps.value.title.indexOf("新增") != -1) {
          drawerProps.value.row.create_at = new Date();
          drawerProps.value.row.create_user = userStore.userInfo._id;
          drawerProps.value.row.clickCount = 0;
        }

        drawerProps.value.row.size = getPlainTextLength(show_content.value);
        if (show_content.value) {
          drawerProps.value.row.content = encryptData(show_content.value);
        }

        if (drawerProps.value.row.show_password && open_password.value) {
          drawerProps.value.row.password = encryptData(drawerProps.value.row.show_password);
        } else {
          drawerProps.value.row.password = "";
        }

        // 保存共享用户信息
        drawerProps.value.row.sharedUsers = selectedUsers.value.map((user: any) => user._id);
        drawerProps.value.row.sharedUserNames = selectedUsers.value.map((user: any) => user.userName);

        const data = await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
        ElMessage.success({ message: `${drawerProps.value.title}成功！` });
        if (drawerProps.value.title.indexOf("新增") != -1) {
          addUserAction(data._id, BusinessOptType.ADD, data.name);
        } else {
          addUserAction(drawerProps.value.row._id, BusinessOptType.UPDATE, drawerProps.value.row.name);
        }
        drawerProps.value.getTableList!();
        drawerVisible.value = false;
      } catch (error) {
        console.log(error);
      }
    });
  } else {
    ElMessage.warning("密码强度不符合，请检查");
  }
};

const getPlainTextLength = (htmlString: string | undefined) => {
  if (htmlString) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlString, "text/html");
    const plainText = doc.body.textContent || "";
    return plainText.length;
  } else {
    return 0;
  }
};

const closeDialog = async () => {
  drawerVisible.value = false;
};

defineExpose({
  acceptParams,
  closeDialog
});
</script>

<style lang="scss" scoped>
.safe-note-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}
.note-form {
  max-height: 75vh;
  padding: 0 20px;
  overflow-y: auto;
}
.form-section {
  margin-bottom: 32px;
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 12px;
    margin-bottom: 20px;
    border-bottom: 2px solid var(--el-border-color-lighter);
    .section-title {
      display: flex;
      gap: 8px;
      align-items: center;
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      .el-icon {
        color: var(--el-color-primary);
      }
    }
  }
}
.password-input {
  display: flex;
  gap: 12px;
  align-items: center;
  .el-input {
    flex: 1;
  }
  .password-strength {
    flex-shrink: 0;
    .success-icon {
      font-size: 18px;
      color: var(--el-color-success);
    }
    .error-icon {
      font-size: 18px;
      color: var(--el-color-danger);
    }
  }
}
.editor-container {
  height: 400px;
  overflow: hidden;
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  :deep(.w-e-text-container) {
    height: 400px !important;
  }
}

// 响应式设计
@media (width <= 768px) {
  .safe-note-dialog {
    :deep(.el-dialog) {
      width: 95vw !important;
      margin: 0 !important;
    }
  }
  .note-form {
    padding: 0 16px;
  }
  .form-section {
    .section-header {
      flex-direction: column;
      gap: 8px;
      align-items: flex-start;
    }
  }
  .password-input {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  .editor-container {
    height: 300px;
    :deep(.w-e-text-container) {
      height: 300px !important;
    }
  }
  .dialog-footer {
    flex-direction: column;
    gap: 8px;
    .el-button {
      width: 100%;
    }
  }
}
</style>
